package com.shujia.control;

import com.shujia.bean.MyList;
import com.shujia.bean.MyString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("redis")
public class RedisControl {

    /**
     * 用于操作Redis相关的内容
     */
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 注意：在SpringBoot中调用Redis中的数据时，要求该数据必须是Spring写入的
     *      ，否则会报序列化错误
     * @return
     */
    @RequestMapping("get")
    public String getSet(){
        // 可以用来操作STRING类型的数据
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("springKey","value1");
        String springKey = (String)valueOperations.get("springKey");
        return springKey;
    }

    /**
     * 在RequestMapping中设置请求方式为POST(由于客户端在访问URL时，需要传入一个对象)
     *      ，而Get请求无法获取对象信息
     *  RequestBody注解表示将Post请求中的对象映射到对应的类参数中
     * @param myList
     * @return
     */
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public String insertList(@RequestBody MyList myList){
        ListOperations listOperations = redisTemplate.opsForList();
        for (String value : myList.getValues()) {
            listOperations.leftPush(myList.getKey(),value);
        }
        return "数据插入成功...";
    }

    @RequestMapping(value = "string",method = RequestMethod.POST)
    public String insertString(@RequestBody MyString myString){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(myString.getKey(),myString.getValue());
        return "数据插入成功...";
    }





}
